import React from "react";
import { Link, useLocation } from "react-router-dom";

import { Menu } from "antd";
const { SubMenu } = Menu;

/**
 * Author: YuBing 羽冰
 *  time : 2021.4.6
 * introduction: cms System Sider component  自制cms侧边栏渲染组件
 *  dependency : react、react-router-dom、antd
 *  need : 
 *    1. setting: the setting(Array) of sider
 *    2. defaultChecked: the defaultChecked when you first go in the page
 *                       just use the path to set it
 *    3. mode: default "inline", other value just find on ant design
 *    4. theme: the theme of sider,default "dark",other value just find on ant design
 *  constitute of setting: 
 *    [{name,path,icon[,children]},{name,path,icon[,children]}···]
 *  constitute of children:
 *    [{name,path,icon[,children]},{name,path,icon[,children]}···]
 *    or
 *    {name,path,icon[,children]}
 * 
 * ps: the prop "path" of setting will be used on component "Menu.Item"'s "path" and "key" atrribute. So we use the "path" prop to set the "defaultChecked"'s value --> defaultChecked={"/userIndex/Index"}
 */

const readSetting = setting => (
  setting.map(item => {
    if (item.children) return (
      <SubMenu
        key={item.path}
        icon={item.icon}
        title={item.name}>
        {readSetting(item.children)}
      </SubMenu>
    )
    return (
      <Menu.Item
        key={item.path}
        icon={item.icon}>
        <Link to={item.path}>{item.name}</Link>
      </Menu.Item>
    )
  })
)

const CmsSider = props => {
  let location = useLocation();
  return (
    <Menu
      theme={props.theme || "dark"}
      defaultSelectedKeys={[props.defaultChecked]}
      selectedKeys={[location.pathname]}
      mode={props.mode || "inline"}>
      {readSetting(props.setting)}
    </Menu>
  )
}

export default CmsSider